package cn.iocoder.yudao.module.infra.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.MDC;
import jakarta.servlet.http.HttpServletRequest;


/**
 * Description:
 * Author: li
 * Date: 2024/3/8
 */
public class TraceIdUtil {
    public static final String TID = "tid";
    public static final String UID = "uid";

    public static void setUserId(Long uid) {
        if (uid == null) {
            return;
        }

        MDC.put(UID, uid.toString());
    }

    public static void removeUserId() {
        MDC.remove(UID);
    }

    public static String setTraceId(String tid) {
        MDC.put(TID, StrUtil.isNotEmpty(tid) ? tid : IdUtil.simpleUUID());
        return tid;
    }

    public static String getTraceId() {
        final String tid = MDC.get(TID);
        return StrUtil.isNotEmpty(tid) ? tid : IdUtil.simpleUUID();
    }

    public static void removeTraceId() {
        MDC.remove(TID);
    }


    public static void setTraceId(HttpServletRequest request, String traceId) {
        TraceIdUtil.setTraceId(traceId);
        request.setAttribute(TID, traceId);
    }

    public static String getTraceId(HttpServletRequest request) {
        String traceId = (String) request.getAttribute(TID);
        if (StrUtil.isEmpty(traceId)) {
            traceId = getTraceId();
        }
        return traceId;
    }

    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
    }

}
